# -*- coding: utf-8 -*-
#!/usr/bin/env bash
pushd `dirname $0` > /dev/null
BASE_DIR=`pwd -P`
popd > /dev/null

#############
# Functions
#############
function logging {
    echo "[INFO] $*"
}
function build_venv {
    cd ${BASE_DIR}
    if [ ! -d env375 ]; then
        virtualenv env375
    fi
    . env375/bin/activate
    pip3 install -r requirements.txt
    cd ${BASE_DIR}/mysite
}

function del_db {
    logging "Clean"
    rm -rf db.sqlite3
    rm -rf account/migrations/0*.py
    rm -rf core/migrations/0*.py

}

function creator_db {
    logging "makemigrations" "account"
    python manage.py makemigrations account

    logging "makemigrations" "core"
    python manage.py makemigrations core

    logging "migrate"
    python manage.py migrate
    
}

function write_data_db {
    logging "initdb.py"
    python initdb.py
}

function launch_webapp {
    python3 manage.py runserver 8080
}
#############
# Main
#############
OPT_ENV_FORCE=$1
build_venv

#创建数据库表，适合添加数据库后操作，能重复操作，不会破坏数据。
if [ "${OPT_ENV_FORCE}x" == "-cx" ];then    
    creator_db
fi
# 创建数据表、创建超级用户，破坏数据?!!!(2018.01.21)。
if [ "${OPT_ENV_FORCE}x" == "-cax" ];then    
    creator_db
    python3 manage.py createsuperuser #创建超级用户
fi

# 初始化数据库。创建数据表,删除数据后再加载数据。谨慎操作！！！
if [ "${OPT_ENV_FORCE}x" == "-ix" ];then    
    del_db
    creator_db
    write_data_db
fi


launch_webapp
